import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/home')
  },
  {
    path: '/shop/:id',
    name: 'Shop',
    component: () => import('@/views/shop')
  },
  {
    path: '/cartList',
    name: 'CartList',
    component: () => import('@/views/cartList')
  },
  {
    path: '/orderConfirm/:shopId',
    name: 'OrderConfirm',
    component: () => import('@/views/orderConfirm')
  },
  {
    path: '/orderList',
    name: 'OrderList',
    component: () => import('@/views/orderList')
  },
  {
    path: '/personCenter',
    name: 'PersonCenter',
    component: () => import('@/views/personCenter')
  },
  {
    path: '/search',
    name: 'Search',
    component: () => import('@/views/search')
  },
  {
    path: '/searchResult',
    name: 'SearchResult',
    component: () => import('@/views/searchResult')
  },
  {
    path: '/addressManage',
    name: 'AddressManage',
    component: () => import('@/views/addressManage')
  },
  {
    path: '/editAddress/:id',
    name: 'EditAddress',
    component: () => import('@/views/addressManage/EditAddress')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login'),
    beforeEnter (to, from, next) {
      const isLogin = localStorage.getItem('isLogin')
      isLogin ? next({ name: 'Home' }) : next()
    }
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const isLogin = localStorage.getItem('isLogin')
  isLogin || to.name === 'Login' ? next() : next({ name: 'Login' })
})

export default router
